package 网络.TCP;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketTCP01Server {
    public static void main(String[] args) throws IOException {
        //在本机的9999端口被监听，等待链接
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("在本机的9999端口被监听，等待链接");
        //如果没有客户端链接9999端口时，程序就会被阻塞，等待链接
        //如果有客户端连接，则会返回socket对象
        //一个ServerSocket可以对应多个Socket
        Socket socket = serverSocket.accept();
        System.out.println("服务单 socket = " + socket.getClass());

        //通过socket.getInputStream()，读取客户端写入的数据通道的数据，显示
        InputStream inputStream = socket.getInputStream();
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(buf)) != -1){
            System.out.println(new String(buf,0,readLen));
        }
        //关闭流和socket
        inputStream.close();
        socket.close();
        serverSocket.close();
    }
}
